/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("cw_djlc_wlzb",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Entity.DomainModels;
using VOL.Finance.IServices;
using Microsoft.AspNetCore.Authorization;
using SapNwRfc;
using System.Configuration;
using VOL.Core.Configuration;
using VOL.Core.Filters;
using System.Linq;
using VOL.Core.DBManager;
using System.Globalization;
using Castle.Core.Internal;

namespace VOL.Finance.Controllers
{
    public partial class cw_djlc_wlzbController
    {
        private readonly Icw_djlc_wlzbService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;

        [ActivatorUtilitiesConstructor]
        public cw_djlc_wlzbController(
            Icw_djlc_wlzbService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }
        /// <summary>
        /// 20230607
        /// U5T4CNH003010P00  U5D6BJS009010E05
        /// https://github.com/huysentruitw/SapNwRfc 
        /// 文档地址
        /// </summary>
        /// <param name="P_DATUB">BOM的有效截止时间</param>
        /// <param name="P_MATNR">BOM的头物料号</param>
        /// <returns></returns>
        [HttpPost, Route("get_sap_bom"), AllowAnonymous ]
        [HttpGet]
        [ApiActionPermission()]
        public dynamic get_sap_bom(string P_DATUB_OUT,string P_MATNR_OUT,string newbomnumber,string cw_djlc_djzb_id)
        {

            string connectionString = AppSetting.GetSection("SAP_ECC_CONN")["connstr"];
            //string connectionString = "AppServerHost=10.100.8.126; SystemNumber=00; User=c000541; Password=5Tgb6yhn; Client=700; Language=ZH; PoolSize=5; Trace=0";//测试系统
            // string connectionString = "AppServerHost=10.100.8.124; SystemNumber=00; User=c000541; Password=2Wsx3edc; Client=700; Language=ZH; PoolSize=5; Trace=0";//正式系统
            using var connection = new SapConnection(connectionString);
            connection.Connect();
            using var someFunction = connection.CreateFunction("ZJRPPI0001");
            List<SomeFunctionitem> ils2 = new List<SomeFunctionitem>();
            var result = someFunction.Invoke<SomeFunctionResult>(new SomeFunctionParameters
            {
                P_DATUB = P_DATUB_OUT,
                P_MATNR= P_MATNR_OUT,
            });
            // Console.WriteLine("exoprt"+result.T_FLAG);
            /* 返回参数 T_FLAG字典值：
                 S: 成功
                 N: 物料不存在
                 E:  未查询到该物料BOM*/
            if (result.T_FLAG == "E")
            {
                return "未查询到该物料BOM"; 
            }
            if (result.T_FLAG == "N")
            {
                return "物料不存在";
            }
            for (int ii = 0; ii < result.T_STPOX.Length; ii++)
            {
                ils2.Add(result.T_STPOX[ii]);
            }
            string[] matnrs = ils2.Select(x => x.IDNRK).ToArray();
            var removedb = DBServerProvider.DbContext.Set<cw_djlc_wlzb>();
            var removedbWljgwh = DBServerProvider.DbContext.Set<cw_djlc_wljgwh>();
            IQueryable<cw_djlc_wlzb> _query = removedb.Where(t => t.bomnumber== newbomnumber).AsQueryable();
            IQueryable<cw_djlc_wljgwh> _query2 = removedbWljgwh.Where(t => t.cw_djlc_djzb_id == Guid.Parse(cw_djlc_djzb_id)).AsQueryable();
            removedb.RemoveRange(_query);
            removedbWljgwh.RemoveRange(_query2);
            DBServerProvider.DbContext.SaveChanges();

            for (int i = 0; i < ils2.Count; i++)
            {
                cw_djlc_wlzb sap_mara = new cw_djlc_wlzb();
                sap_mara.materialnum = P_MATNR_OUT;
                sap_mara.parent_componentnum = ils2[i].MATNR;
                sap_mara.componentnum = ils2[i].IDNRK;
                sap_mara.MTyp = ils2[i].MTART;
                sap_mara.description = ils2[i].MAKTX;
                sap_mara.num = ils2[i].MENGE;
                sap_mara.bomeffectivedatestart = ils2[i].DATUV == null ? null : DateTime.ParseExact(ils2[i].DATUV, "yyyyMMdd", CultureInfo.CurrentCulture);
                sap_mara.bomeffectivedateend = ils2[i].DATUB == null ? null : DateTime.ParseExact(ils2[i].DATUB, "yyyyMMdd", CultureInfo.CurrentCulture);
                sap_mara.bomtype = 2;
                sap_mara.bomnumber = newbomnumber;
                sap_mara.cw_djlc_djzb_id = Guid.Parse(cw_djlc_djzb_id);
                Guid wlzbId = Guid.NewGuid();
                sap_mara.cw_djlc_wlzb_id = wlzbId;
                sap_mara.Creator = "SAP";
                sap_mara.CreateDate = DateTime.Now;
                sap_mara.evaluation_code = ils2[i].BKLAS;
                sap_mara.evaluation_desc = ils2[i].BKBEZ;
                /*    sap_mara.description = ils2[i].MAKTX;
                    sap_mara.description = ils2[i].MAKTX;
                    sap_mara.description = ils2[i].MAKTX;*/
                removedb.Add(sap_mara);

                //添加 物料价格维护关系
                cw_djlc_wljgwh cdw = new cw_djlc_wljgwh();
                cdw.cw_djlc_djzb_id = Guid.Parse(cw_djlc_djzb_id);
                cdw.cw_djlc_wlzb_id = wlzbId;
                removedbWljgwh.Add(cdw);
            }
            DBServerProvider.DbContext.SaveChanges();
            return ils2.Count;
        }
        /// <summary>
        /// 输入参数
        /// </summary>
        class SomeFunctionParameters
        {
            [SapName("P_DATUB")]
            public string P_DATUB { get; set; }
            [SapName("P_MATNR")]
            public string P_MATNR { get; set; }
        }

        /// <summary>
        /// 输出参数名称
        /// </summary>
        class SomeFunctionResult
        {
            [SapName("T_STPOX")]
            public SomeFunctionitem[] T_STPOX { get; set; }

            [SapName("T_FLAG")]//接受Export传出参数
            public string T_FLAG { get; set; }

        }
        /// <summary>
        /// 对应的SAP中返回的结构
        /// </summary>
        public class SomeFunctionitem
        {
            //[SapName("MATNR")]//可以不用
            public string MATNR { get; set; }
            //[SapName("WERKS")]
            public string IDNRK { get; set; }//BOM 组件
            public string MTART { get; set; }//物料类型
            public string MAKTX { get; set; }//物料描述（短文本）
            public decimal MENGE { get; set; }//组件数量
            public string MEINS { get; set; }//组件计量单位
            public string DATUV { get; set; }//有效起始日期
            public string DATUB { get; set; }//有效截止日期
            public string ANDAT { get; set; }//日期记录创建于
            public string BKLAS { get; set; }//评估类 
            public string BKBEZ { get; set; }//评估类的描述
            // [SapName("MAKTX")]

        }
        /// <summary>
        /// 20230607
        /// U5D6BJS009010E05
        /// </summary>
        /// <param name="P_MATNR">通过BOM的头物料号获取价格</param>
        /// <param name="bomnumber"></param>
        /// <returns></returns>
        [HttpPost, Route("get_sap_price_tou"), AllowAnonymous]
        [HttpGet]
        [ApiActionPermission()]
        public dynamic get_sap_price_tou(string P_MATNR,string bomnumber)
        {

            List<cw_djlc_wlzb> cw_djlc_wlzb_list= DBServerProvider.DbContext.Set<cw_djlc_wlzb>().Where(w=>w.materialnum== P_MATNR && w.bomnumber== bomnumber).ToList();
            matnrs_in[] matnrs_in_array = cw_djlc_wlzb_list.Select(s => new matnrs_in
            {
                //MATNR = s.componentnum.ToString().PadLeft(18, '0').ToString()
                MATNR = s.componentnum.ToString()
            }).ToArray();
            //return matnrs_in_array;
            string connectionString = AppSetting.GetSection("SAP_ECC_CONN")["connstr"];
            using var connection = new SapConnection(connectionString);
            connection.Connect();
            using var someFunction = connection.CreateFunction("ZJRPPI0002");
            List<Someitem> ils2 = new List<Someitem>();
            var result = someFunction.Invoke<Result_price>(new SomeFunctionParameters_price
            {
                 T_MATNR = matnrs_in_array,
            });
            for (int i = 0; i < cw_djlc_wlzb_list.Count; i++)
            {
                // var ttt = result.T_MATPRI.Where(w => w.MATNR == cw_djlc_wlzb_list[i].componentnum.ToString().PadLeft(18, '0').ToString());
                var ttt = result.T_MATPRI.Where(w => w.MATNR == cw_djlc_wlzb_list[i].componentnum.ToString());
                string priceeffectivedatestart = ttt.Select(s => s.DATAB).FirstOrDefault();
                string priceeffectivedateend = ttt.Select(s => s.DATBI).FirstOrDefault();
                //cw_djlc_wlzb_list[i].priceeffectivedatestart = ttt.Select(s => s.DATAB).FirstOrDefault()==null?null:DateTime.ParseExact(ttt.Select(s => s.DATAB).FirstOrDefault()??"", "yyyyMMdd", CultureInfo.CurrentCulture);
                //cw_djlc_wlzb_list[i].priceeffectivedateend = ttt.Select(s => s.DATBI).FirstOrDefault()==null?null:DateTime.ParseExact(ttt.Select(s => s.DATBI).FirstOrDefault() ?? "", "yyyyMMdd", CultureInfo.CurrentCulture);
                if (!priceeffectivedatestart.IsNullOrEmpty() && !priceeffectivedatestart.Equals("00000000"))
                {
                    cw_djlc_wlzb_list[i].priceeffectivedatestart = DateTime.ParseExact(priceeffectivedatestart, "yyyyMMdd", CultureInfo.CurrentCulture);
                }
                if (!priceeffectivedateend.IsNullOrEmpty() && !priceeffectivedateend.Equals("00000000"))
                {
                    cw_djlc_wlzb_list[i].priceeffectivedateend = DateTime.ParseExact(priceeffectivedateend, "yyyyMMdd", CultureInfo.CurrentCulture);
                }
                cw_djlc_wlzb_list[i].codename = ttt.Select(s => s.LIFNR).FirstOrDefault();
                //cw_djlc_wlzb_list[i].unitprice= ttt.Select(s => s.PRICE).FirstOrDefault();

                var unitprice = ttt.Select(s => s.PRICE).FirstOrDefault();
                if (!unitprice.Equals("0.00")|| !unitprice.Equals("0"))
                {
                    cw_djlc_wlzb_list[i].unitprice = unitprice; //sap 同步过来的价格
                }
                else
                {
                    //sap没有价格，从估价库里取价格,如果估价库里没有找到 赋值0;
                    cw_djlc_assess assess = DBServerProvider.DbContext.Set<cw_djlc_assess>().Where(s => s.materialnum == cw_djlc_wlzb_list[i].componentnum).ToList().FirstOrDefault();
                    if (assess!=null)
                    {
                        cw_djlc_wlzb_list[i].unitprice = assess.price;
                    }
                    else
                    {
                        cw_djlc_wlzb_list[i].unitprice = 0;
                    }
                }
                DBServerProvider.DbContext.Update(cw_djlc_wlzb_list[i]);
            }
            DBServerProvider.DbContext.SaveChanges();
            return result.T_MATPRI.Length;
        }

        class matnrs_in
        {
            [SapName("MATNR")]
            public string MATNR { get; set; }
        }
        /// 输入参数
        /// </summary>
        class SomeFunctionParameters_price
        {
            [SapName("T_MATNR")]
            public matnrs_in[] T_MATNR { get; set; }
        }
        /// <summary>
        /// 价格输出参数名称
        /// </summary>
        class Result_price
        {
            [SapName("T_MATPRI")]
            public Someitem[] T_MATPRI { get; set; }

        }
        /// <summary>
        /// 对应的价格SAP中返回的结构
        /// </summary>
        public class Someitem
        {
            //[SapName("MATNR")]//可以不用
            public string MATNR { get; set; }//物料号
            //[SapName("WERKS")]
            public string LIFNR { get; set; }//供应商或债权人的帐号
            public string KNUMH { get; set; }//条件记录号
            public decimal PRICE { get; set; }//价格(条件金额或百分数 ) 无等级存在
            public string DATAB { get; set; }//条件记录有效起始日
            public string DATBI { get; set; }//条件记录有效截止日期
            public string KZUST { get; set; }//SD中条件/物料责任


        }
    }
}
